import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
import { Radio } from 'antd';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon, WeaTools } from 'ecCom';
import { AntdConfirm } from '../util';
import Preview from './Preview';
import Edit from './Edit';

const Base64 = WeaTools.Base64;
const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'TEMPLATE';

@inject('settingStore')
@observer
class Template extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-template',
  };

  constructor(props) {
    super(props);
    this.state = {
      editVisible: false,
    };
  }

  componentWillMount() {
    const {
      settingStore: { templateStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: () => templateStore.getMailTemplate(),
      },
    ];
    setStoreState({ rightMenuDatas });
    templateStore.getMailTemplate();
  }

  componentWillUnmount() {
    const {
      settingStore: { templateStore },
    } = this.props;
    templateStore.clear();
  }

  onOperatesClick = (record, index, operate) => {
    if (operate.index === '0') {
      // edit
      this.editTemplate(record);
    } else if (operate.index === '1') {
      // preview
      this.previewTemplate(record);
    } else if (operate.index === '2') {
      // delete
      this.batchDel(record.randomFieldId);
    }
  };

  batchDel = (id) => {
    const {
      settingStore: { templateStore },
    } = this.props;
    const { templateTable, operateUserMailTemplate } = templateStore;
    let mailTemplateIDs =
      id || toJS(templateTable.selectedRowKeysAllPages).join();
    AntdConfirm('', () => {
      operateUserMailTemplate({ operation: 'delete', mailTemplateIDs });
    });
  };

  editTemplate = (record) => {
    const {
      settingStore: { templateStore },
    } = this.props;
    const {
      getMailTemplateBean,
      setStoreState,
      getEmailTemplateCondition,
      editForm,
    } = templateStore;
    getEmailTemplateCondition('', () => {
      getMailTemplateBean({
        id: record.randomFieldId,
        templateType: record.templateType,
      }).then((res) => {
        const { emailTemplateBean } = res;
        const editRichValue =
          Base64.decode(emailTemplateBean.templateContent) || '';
        for (let attr in emailTemplateBean) {
          editForm.updateFields({ [attr]: { value: emailTemplateBean[attr] } });
        }
        setStoreState({
          editRichValue,
          editTitle: getLabel(28052, '编辑模板'),
          editId: record.randomFieldId,
          editType: record.templateType,
        });
        this.setState({ editVisible: true });
      });
    });
  };

  previewTemplate = (record) => {
    const {
      settingStore: { templateStore },
    } = this.props;
    const {
      getMailTemplateBean,
      setStoreState,
      getEmailSysTemplateCondition,
      previewForm,
    } = templateStore;
    getEmailSysTemplateCondition({ type: 'view' }, () => {
      getMailTemplateBean({
        id: record.randomFieldId * -1,
        templateType: record.templateType,
      }).then((res) => {
        const { docMailMouldBean } = res;
        for (let attr in docMailMouldBean) {
          previewForm.updateFields({
            [attr]: { value: docMailMouldBean[attr] },
          });
        }
        previewForm.updateFields({
          mouldtype: { value: getLabel(83158, '系统模板') },
        });
        setStoreState({ previewVisible: true });
      });
    });
  };

  radioChange = (e, record) => {
    const {
      settingStore: { templateStore },
    } = this.props;
    let defaultMailTemplateID =
      record.templateType === '1'
        ? record.randomFieldId * -1
        : record.randomFieldId;
    templateStore.operateUserMailTemplate({
      operation: 'default',
      defaultMailTemplateID,
      templateType: record.templateType,
    });
  };

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === 'id') {
          return (
            <Radio
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Radio@rmufik@${MAILPAGENAME}${record.randomFieldId}`}
              type="checkbox"
              checked={record.isDefault * 1 === 1}
              onChange={e => this.radioChange(e, record)}
            />
          );
        } else if (newColumn.dataIndex == 'name') {
          return (
            <div
              onClick={() =>
                (record.templateType * 1
                  ? this.previewTemplate(record)
                  : this.editTemplate(record))
              }
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };
  onAddTemp = () =>
    this.refs.editTemplate.wrappedInstance.newTemplate('', () =>
      this.setState({ editVisible: true }),
    );
  onEditCancel = () => this.setState({ editVisible: false });
  onEditSubmit = () => {
    const {
      settingStore: { templateStore },
    } = this.props;
    templateStore.getMailTemplate('', true);
  };

  render() {
    const {
      prefixCls,
      settingStore: { templateStore },
    } = this.props;
    const { templateTable } = templateStore;
    const tabButtons = [
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@ly3mi3@${MAILPAGENAME}add`}
        buttonType="add"
        type="primary"
        onClick={this.onAddTemp}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@w7k2hu@${MAILPAGENAME}del`}
        buttonType="del"
        type="primary"
        disabled={toJS(templateTable.selectedRowKeysAllPages).length === 0}
        onClick={() => this.batchDel()}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@5pxnn8`}
          datas={[{ title: getLabel(17858, '模板列表'), viewcondition: '0' }]}
          keyParam="viewcondition"
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@vsgzkt`}
          comsWeaTableStore={templateTable}
          getColumns={this.getColumns}
          onOperatesClick={this.onOperatesClick}
          needScroll
          hasOrder
        />
        <Preview
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Preview@x2e0he`}
          class={prefixCls}
        />
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@ilpimj`}
          ref="editTemplate"
          visible={this.state.editVisible}
          onCancel={this.onEditCancel}
          onSubmit={this.onEditSubmit}
        />
      </div>
    );
  }
}

export default Template;
